//
//  RegistrationButtonCell.swift
//  PorscheRegistration
//
//  Created by Jinzhu Liu on 2023/11/16.
//

import UIKit

class RegistrationButtonCell: NiblessTableViewCell, ViewModelUpdatableCell {
    var viewModel: AnyObject?

    var submitButton: UIButton
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        self.submitButton = UIButton(type: .custom)
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func setupUI() {
        self.contentView.addSubview(submitButton)
        submitButton.backgroundColor = UIColor(red: 0.5, green: 0.5, blue: 1.0, alpha: 1.0)
        submitButton.setTitleColor(.white, for: .normal)
        submitButton.setTitle("Submit", for: .normal)
        submitButton.layer.cornerRadius = 20.0
        submitButton.clipsToBounds = true
        submitButton.addTarget(self, action: #selector(buttonTouched(sender:)), for: .touchUpInside)
        submitButton.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            submitButton.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            submitButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
            submitButton.heightAnchor.constraint(equalToConstant: 40.0),
            submitButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10.0),
            submitButton.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10.0)
        ])
    }
    
    @objc private func buttonTouched(sender: AnyObject) {
        guard let buttonViewModel = viewModel as? RegistrationButtonCellViewModelType else {
            return
        }
        buttonViewModel.input.submitData()
    }
    
    func update(with viewModel: AnyObject?) {
        self.viewModel = viewModel
    }
}
